var app = getApp()
const { default: Toast } = require("../../component/vant/toast/toast.js");
var fetchApi = require("../../utils/httpPost.js");
Page({
  data: {
    imgurl: app.getImgUrl(),
    userInfo: {},
    hasUserInfo: false,
    is_mer: 0,
    is_admin: 0,
    shop_id:0,
    orderItemArr: [],
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    adBanner: [],
    hasBanner: false,
    total_integral: 0,
    shop_type: 0,
    isLoading: false,
    ag_id:0,
    from_type:'',
    isEgg:0,
    device_id:0,
    ticket_id:0,
    product_id:0,
    promoter_id:0,//推广员id
    m_no:'',
    jd:0,
    wd:0,
    showTransition:false,
    submitState:false,
  },
  onLoad: function (options) {
    // this.modalcnt();
    var that = this;
    if(options.from_type){
      this.data.from_type = options.from_type;

      if(options.from_type == 'takeup'){
        if(options.id){
          this.data.device_id = options.id;
        }
      } else if(options.from_type == 'product'){
        if(options.id){
          this.data.product_id = options.id;
        }
      }
    }

    if(options.isEgg){
      this.data.isEgg = options.isEgg;
    }
    if(options.ticket_id){
      this.data.ticket_id = options.ticket_id;
    }

    if(options.ag_id){
      this.data.ag_id = parseInt(options.ag_id)
    }else{
      if(app.getStorageSync("ag_id")!=undefined && app.getStorageSync("ag_id")!=''){
        this.data.ag_id = parseInt(app.getStorageSync("ag_id"));
      }
    }

    if(options.promoter_id){
      this.data.promoter_id = parseInt(options.promoter_id)
    }else{
      console.log('app.getStorageSync("promoter_id")',app.getStorageSync("promoter_id"))
      if(app.getStorageSync("promoter_id")!=undefined && app.getStorageSync("promoter_id")!=''){
        this.data.promoter_id = parseInt(app.getStorageSync("promoter_id"));
      }
    }

    if(options.m_no){
        this.data.m_no = options.m_no;
    }
    
    var isLogin = app.getStorageSync("isLogin");
    if(isLogin){
      wx.redirectTo({
        url: 'pages/home/home',
      })
    }
  },
  onGetUserInfo:function(e){
    wx.getUserProfile({
      desc: '用与获取用户信息',
      success:(res)=>{
        console.log('onGetUserInfo ',res)
        // this.loginOp(res)
        this.modalcnt(res);
      }
    })
  },
  onShow(){
    console.log('onShow');
    // this.modalcnt();
  },
  modalcnt:function  (res_user)  {
    var  that  =  this;
    //获取经纬度  
    wx.getLocation({
      type:  'gcj02',
      success: function  (res)  {
        console.log('modalcnt', res)
        var latitude = res.latitude
        var longitude = res.longitude
        that.data.wd = latitude//纬度
        that.data.jd = longitude//经度
        that.setData({
          wd : latitude,
          jd : longitude
        })
        app.setStorageSync("lng",longitude);
        app.setStorageSync("lat",latitude);

        console.log('longitude',longitude)
        console.log('latitude',latitude)

        that.loginOp(res_user);
      },fail:function(res){
        that.data.wd = 0;
        that.data.jd = 0;
        app.setStorageSync("lng",0);
        app.setStorageSync("lat",0);
        console.log('longitude',0)
        console.log('latitude',0)
        // if(lng == undefined || lng == '' || lng == 0){
        //   Toast.fail("请开启您的定位");
        //   return;
        // }
        that.loginOp(res_user);
      }
    })
  },
  goTeaching(e){
    this.setData({
      showTransition: !this.data.showTransition
    })
  },
  hideMask(e){
    this.setData({
      showTransition: !this.data.showTransition
    })
  },
  loginOp: function (res_user) {
    if(this.data.submitState == true){
      Toast("登录中，请稍后...");
      return;
    }
    var that = this
    app.setStorageSync("isLogin",0);
    // if(lng == undefined || lng == '' || lng == 0){
    //   Toast.fail("请开启您的定位");
    //   return;
    // }else{
    // }
    this.data.submitState = true;
    this.setData({
      submitState:true
    })
    this.onHttpLogin(res_user);
  },
  onHttpLogin(res_user){
    var that = this;
    that.setData({ isLoading: true});
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log("code", res.code)
        fetchApi.httpPost('/user/wxLogin', { 
          code: res.code ,
          ag_id: that.data.ag_id,
          promoter_id:that.data.promoter_id,
          m_no: that.data.m_no,//商家编号
          platform:"bingge",
          from_type: that.data.from_type,
          lng:that.data.jd,
          lat:that.data.wd,
        }, function (res_login) {
          console.log("登录返回数据", res_login);
          if(res_login.data.code == 0){
            app.globalData.user_id = res_login.data.data.user_id;
            app.globalData.is_mer = res_login.data.data.is_mer;
            app.setStorageSync('isLogin',1);
            app.setStorageSync('user_id', res_login.data.data.user_id);
            app.setStorageSync('access_token', res_login.data.data.access_token);
            app.setStorageSync('is_mer', res_login.data.data.is_mer);
            app.setStorageSync('is_admin', res_login.data.data.is_admin);
            app.setStorageSync('is_super_admin', res_login.data.data.is_super_admin);
            app.setStorageSync('is_new_user', res_login.data.data.is_new_user);

            app.globalData.userInfo = res_user.userInfo
            app.setStorageSync('userInfo', res_user.userInfo);
            console.log('res_user', res_user)
            if(res_user.errMsg == 'getUserInfo:fail auth deny'){
              app.setStorageSync("isLogin",0);
              var pages = getCurrentPages();
              var prevPage = pages[pages.length - 2]; //上一个页面
              console.log('res_user', res_user)
              //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
              prevPage.setData({
                from_page: 'login',
                id: that.data.device_id,
                isEgg: that.data.isEgg,
                ticket_id: that.data.ticket_id,
              })
              wx.navigateBack({ delta: 1 });
              // Toast.fail('登录失败11')
            }else{
              fetchApi.httpPost('/user/getUserInfo', {
                iv: res_user.iv,
                encryptedData: res_user.encryptedData,
                rawData: res_user.rawData,
                userInfo:app.globalData.userInfo,
              }, function (res_info) {
                console.log('res_info', res_info)
                var pages = getCurrentPages();
                console.log('pages',pages)
                var prevPage = pages[pages.length - 2]; //上一个页面
                console.log('pages prevPage 1',prevPage)
                //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
                if(that.data.from_type == 'takeup'){
                  prevPage.setData({
                    from_page: 'login',
                    device_id: that.data.device_id,
                    isEgg: that.data.isEgg,
                    ticket_id: that.data.ticket_id,
                  })
                } else if(that.data.from_type == 'product'){
                  prevPage.setData({
                    from_page: 'login',
                    id: that.data.product_id,
                  })
                }else{
                  prevPage.setData({
                    from_page: 'login',
                  })
                }
                console.log('pages prevPage 2 ',prevPage)
                wx.navigateBack({ delta: -1 });
              }, function () { })
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (that.userInfoReadyCallback) {
                console.log('发起回调')
                that.userInfoReadyCallback(res_user)
              }
            }
          }else{
            wx.showToast({
              title: '登录失败',
            })
          }
          that.data.submitState = false;
          that.setData({
            submitState:false
          })
          that.setData({ isLoading: false, loading: true })
        }, function () { })
      },fail(){
        that.data.submitState = false;
        that.setData({
          submitState:false
        })
        that.setData({ isLoading: false, loading: true })
      }
    });
  }
})
